package com.wl.dzt.sys.controller.action;

import com.wl.dzt.sys.controller.param.Param;
import com.wl.dzt.sys.controller.result.ActionResult;
import com.wl.dzt.sys.controller.result.TableResult;
import com.wl.dzt.sys.core.dao.DB;
import com.wl.dzt.sys.core.dao.curd.sql.Sql;
import com.wl.dzt.sys.core.dao.curd.sql.SqlSearchResult;
import com.wl.dzt.sys.core.dao.select.Select;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/5/005
 * @description 查询动作
 * 用于执行查询请求
 * 根据参数执行查询动作
 */
@Component
public class SelectAction implements Action {

    public ActionResult doAction(Param param) {
        ActionResult actionResult = new ActionResult();
        Select select = param.toSelect();
        TableResult tableResult = new TableResult();
        List<Map<String, Object>> data = new ArrayList<>();
        Integer count = 0;
        if (param.getSqlKey() != null) {
            select.setSqlExp(Sql.ALL.get(param.getSqlKey()));
            SqlSearchResult result = DB.selectBySqlExp(select);
            count = result.getCount();
            data = result.getData();
        } else {
            data = DB.listByMap(select);
            count = DB.count(select);
        }

        if (param.getDataChangeter() != null) {
            param.getDataChangeter().change(data);
        }
        tableResult.setData(data);
        tableResult.setCount(count);
        actionResult.setTableResult(tableResult);
        return actionResult;
    }

}
